package com.tea.funct.utils.util;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tea.common.config.TeawineConfig;
import com.tea.common.utils.StringUtils;
import com.tea.common.utils.file.FileUploadUtils;
import com.tea.funct.domain.TeaFixation;
import com.tea.funct.service.ITeaFixationService;
import com.tea.funct.utils.domain.Poster;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.CopyOption;

/**
 * @PACKAGE_NAME: com.tea.funct.utils.util
 * @CLASSNAME: MiniCodePosterUtil
 * @DEACRIPTION: 小程序推广码、推广海报生成工具
 * @AUTHOR: GuoChen
 * @DATE: 2024/6/10
 * @WEEK: 周一
 **/
@Slf4j
@Component
public class MiniCodePosterUtil {

    // 小程序推广码生成目录
    public static final String CODE_DIR_NAME = "referralCode";
    // 推广海报生成目录
    public static final String POSTER_DIR_NAME = "posterImage";

    @Autowired
    private WxMaQrcodeService wxMaQrcodeService;
    @Autowired
    private ITeaFixationService teaFixationService;


    /**
     * 生成小程序推广二维码
     *
     * @param referralCode 用户推荐码
     * @return
     */
    public String createMiniQrCodeByReferralCode(String referralCode) {
        try {
            String filePath = TeawineConfig.getUploadPath() + File.separator + CODE_DIR_NAME + File.separator;
            File file = wxMaQrcodeService.createWxaCodeUnlimit(referralCode, null, filePath);
            String fileExtension = com.tea.common.utils.file.FileUtils.getFileExtension(file.getName());
            String codeFilePath = filePath + referralCode + fileExtension;
            File newFilePath = new File(codeFilePath);
            if (newFilePath.exists()) {
                log.info("小程序推广码已存在，需删除后重新生成！");
                newFilePath.delete();
            }
            FileUtils.moveFile(file, newFilePath);
            MultipartFile multipartFile = FileUploadUtils.fileConvertToMultipartFile(newFilePath);
            String fileName = FileUploadUtils.upload(TeawineConfig.getUploadPath(), multipartFile);
            return fileName;
        } catch (Exception e) {
            log.error("生成小程序二维码出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 根据动态配置生成用户推广海报
     *
     * @param miniQrCodePath 小程序二维码所在路径
     * @return
     */
    public String createPushPoster(String miniQrCodePath, String referralCode) {
        try {
            String bgImagePath = TeawineConfig.getUploadPath() + File.separator + "poster_bg_image.jpg";
            TeaFixation teaFixation = teaFixationService.selectTeaFixationByFeild("dynamiPosterConfig");
            String posterBgPath = teaFixation.getFixationImgPath();
            String fixationImgConf = teaFixation.getFixationImgConf();
            Integer bgWidth = 1280;
            Integer bgHeight = 2556;
            Integer miniCodeWidth = 260;
            Integer miniCodeHeight = 260;
            Integer xAxisPixel = 510;
            Integer yAxisPixel = 2100;
            if (teaFixation != null) {
                // 动态加载背景图片所在路径
                bgImagePath = TeawineConfig.getUploadPath() + File.separator + posterBgPath.replace("/profile/upload", "");
                if (StringUtils.isNotBlank(fixationImgConf)) {
                    log.info("海报配置信息不为空, 则按照配置合成推广海报{}", fixationImgConf);
                    JSONObject confJson = JSONUtil.parseObj(fixationImgConf);
                    bgWidth = confJson.getInt("bgWidth"); // 背景图宽
                    bgHeight = confJson.getInt("bgHeight"); // 背景图高
                    miniCodeWidth = confJson.getInt("miniCodeWidth"); // 小程序二维码宽
                    miniCodeHeight = confJson.getInt("miniCodeHeight"); // 小程序二维码高
                    xAxisPixel = confJson.getInt("xAxisPixel"); // 合成后小程序所占X轴起始像素
                    yAxisPixel = confJson.getInt("yAxisPixel"); // 合成后小程序所占Y轴起始像素
                } else {
                    log.info("推广海报配置为空，则按照默认配置进行!");
                }
            } else {
                log.info("未查询到海报推广配置信息, 则按照默认配置进行合成!");
            }
            // 小程序二维码所在目录
            String codeFilePath = TeawineConfig.getUploadPath() + File.separator + miniQrCodePath.replace("/profile/upload", "");
            // 用户推广海报生成目录
            String poserImageDir = TeawineConfig.getUploadPath() + File.separator + POSTER_DIR_NAME;
            // 用户推广海报生成路径
            String poserImagePath = poserImageDir + File.separator + referralCode + "_poster" + ".png";

            Poster poster = new Poster(bgImagePath, null, bgWidth, bgHeight);
            poster.addImageItem(xAxisPixel, yAxisPixel, miniCodeWidth, miniCodeHeight, codeFilePath);
            BufferedImage bufferedImage = PosterUtil.generatePoster(poster);
            File file = new File(poserImagePath);
            /*if (file.exists()) {
                log.info("海报推广码已存在，需重新生成！");
                file.delete();
            }*/
            ImageIO.write(bufferedImage, "png", file);
            MultipartFile multipartFile = FileUploadUtils.fileConvertToMultipartFile(file);
            String fileName = FileUploadUtils.upload(TeawineConfig.getUploadPath(), multipartFile);
            return fileName;
        } catch (Exception e) {
            log.error("生成用户推广海报出现异常：{}", e.getMessage());
            log.error(e.getMessage(), e);
        }
        return "";
    }

}
